package cn.sylinx.horm.core.datasource;

import cn.sylinx.horm.util.ClassUtil;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

enum DataSourceShutterManager {

    INSTANCE;

    private final List<DataSourceShutter> dataSourceShutterList = new ArrayList<>();

    DataSourceShutterManager() {
        loadFromService();
    }

    private final void loadFromService() {
        ServiceLoader<DataSourceShutter> serviceLoader = ServiceLoader.load(DataSourceShutter.class,
                ClassUtil.getDefaultClassLoader());
        for (DataSourceShutter dataSourceShutter : serviceLoader) {
            dataSourceShutterList.add(dataSourceShutter);
        }
    }

    boolean close(DataSource dataSource) {

        for (DataSourceShutter dataSourceShutter : dataSourceShutterList) {
            if (dataSourceShutter.close(dataSource)) {
                return true;
            }
        }
        return false;
    }
}
